<template>
  <div>
    <el-form :inline="true" class="search-form">
      <el-form-item label="餐厅ID">
        <el-select v-model="searchRestaurantId">
          <el-option :label="item.name" :value="item.id" v-for="item in restaurants" :key="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchCategories" :disabled="searchRestaurantId===''">查询</el-button>
        <el-button type="success" @click="addCategory">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="categories" style="width: 100%">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="restaurantId" label="餐厅ID"></el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button size="small" type="primary" @click="editCategory(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteCategory(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="margin-top: 10px"
        small
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="mt-4"
    />
    <el-dialog title="编辑分类" v-model="dialogVisible">
      <el-form ref="categoryForm" :model="currentCategory" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="currentCategory.name"></el-input>
        </el-form-item>
        <el-form-item label="餐厅ID" prop="restaurantId">
          <el-select v-model="currentCategory.restaurantId">
            <el-option :label="item.name" :value="item.id" v-for="item in restaurants" :key="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCategory">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {reactive, toRefs} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {
  createCategory, deleteCategoryById,
  getAllCategory,
  getCategoryById,
  getCategoryByRestaurantId,
  updateCategory
} from "@/api/category";
import {getRestaurantList} from "@/api/restaurant";

export default {
  setup() {
    const state = reactive({
      categories: [], // 分类数据
      total: 10, // 数据总数
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      currentCategory: null, // 当前编辑的分类对象
      dialogVisible: false, // 编辑对话框是否可见
      rules: { // 表单验证规则
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
        ],
      },
      searchRestaurantId: '', // 查询指定餐厅下的菜品类别的餐厅ID
      restaurants: [],
      isEdit: false, // 是否是编辑
    })
    // 获取分类数据
    const getCategories = async () => {
      try {
        const response = await getAllCategory({page: state.currentPage, pageSize: state.pageSize})
        if (response.msg === '请求成功') {
          state.categories = response.data.list
          state.total = response.data.total
        } else {
          ElMessage.error('获取分类数据失败')
        }
      } catch (e) {
        ElMessage.error('获取分类数据失败')
        console.log(e)
      }
    }
    // 获取餐厅数据
    const getRestaurants = async () => {
      try {
        const response = await getRestaurantList()
        if (response.msg === '请求成功') {
          state.restaurants = response.data
        } else {
          ElMessage.error('获取餐厅数据失败')
        }
      } catch (e) {
        ElMessage.error('获取餐厅数据失败')
        console.log(e)
      }
    }
    // 查询指定餐厅下的菜品类别
    const searchCategories = async () => {
      const restaurantId = state.searchRestaurantId
      if (!restaurantId) {
        ElMessage.error('请选择餐厅')
        return
      }
      try {
        const response = await getCategoryByRestaurantId({
          id: restaurantId,
          page: state.currentPage,
          limit: state.pageSize
        })
        if (response.msg === '请求成功') {
          state.categories = response.data.list
          state.total = response.data.total
        } else {
          ElMessage.error('获取分类数据失败')
        }
      } catch (e) {
        console.log(e)
      }
    }
    // 新增分类
    const addCategory = () => {
      state.currentCategory = {}
      state.dialogVisible = true
    }
    // 编辑分类
    const editCategory = async (row) => {
      try {
        const response = await getCategoryById(row.id)
        if (response.msg === '请求成功') {
          state.currentCategory = response.data
          state.dialogVisible = true
          state.isEdit = true
        } else {
          ElMessage.error('获取分类数据失败')
        }
      } catch (e) {
        ElMessage.error('获取分类数据失败')
        console.log(e)
      }
    }
    // 保存分类
    const saveCategory = async () => {
      if (state.isEdit) {
        const id = state.currentCategory.id
        const saveObj = {
          name: state.currentCategory.name,
          restaurantId: state.currentCategory.restaurantId
        }
        try {
          await updateCategory(id, saveObj)
          ElMessage.success('保存分类成功')
        } catch (e) {
          console.log(e)
          ElMessage.error('保存分类失败')
        }
      } else {
        console.log(state.currentCategory)
        const saveObj = {
          name: state.currentCategory.name,
          restaurantId: state.currentCategory.restaurantId
        }
        try {
          await createCategory(saveObj)
          ElMessage.success('创建分类成功')
        } catch (e) {
          console.log(e)
          ElMessage.error('创建分类失败')
        }
      }
      state.dialogVisible = false
      if (state.searchRestaurantId) {
        await searchCategories()
      } else {
        await getCategories()
      }
    }
    // 删除分类
    const deleteCategory = (row) => {
      ElMessageBox.confirm('确定删除该分类吗?', '提示', {
        type: 'warning',
      }).then(async () => {
        try {
          await deleteCategoryById(row.id)
          ElMessage.success('删除成功')
          if (state.searchRestaurantId) {
            await searchCategories()
          } else {
            await getCategories()
          }
        } catch (e) {
          ElMessage.error('删除失败')
          console.log(e)
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    // 分页器页码大小变化回调
    const handleSizeChange = (pageSize) => {
      state.pageSize = pageSize
      if(state.searchRestaurantId) {
        searchCategories()
      } else {
        getCategories()
      }
    }
    // 分页器当前页码变化回调
    const handleCurrentChange = (currentPage) => {
      state.currentPage = currentPage
      if(state.searchRestaurantId) {
        searchCategories()
      } else {
        getCategories()
      }
    }
    const categoryInit = () => {
      // 初始化加载分类数据
      getCategories()
      getRestaurants()
      state.isEdit = false
    }
    categoryInit()
    // 返回响应式数据
    return {
      ...toRefs(state),
      editCategory,
      saveCategory,
      deleteCategory,
      handleSizeChange,
      handleCurrentChange,
      getCategories,
      searchCategories,
      addCategory
    }
  }
}

</script>
<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  background-color: #fff;
}
</style>
